package com.quanyue.haircut.user.controller;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.auto.util.ServiceResult;
import com.quanyue.auto.web.Principal;
import com.quanyue.auto.web.RequestContext;
import com.quanyue.auto.web.Scope;
import com.quanyue.haircut.domain.constant.UserRole;
import com.quanyue.haircut.domain.entity.User;
import com.quanyue.haircut.user.mapper.UserMapper;
import com.quanyue.haircut.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Api(tags = "用户")
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "测试登录")
    @GetMapping(value = "/user/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void testLogin(@RequestParam("username") String nickName,
                          @ApiIgnore HttpServletResponse response,
                          @ApiIgnore RequestContext context) throws IOException {
        User user = userService.findByName(nickName);
        AssertUtils.notNull(user, "用户不存在");
        context.updatePricipal(new Principal(user.getId(), user.getMerchantNo(), "USER", "WECHAT_MP"));
        response.sendRedirect("/home");
    }

    @ApiOperation(value = "用户列表")
    @Scope(role = UserRole.MANAGER)
    @GetMapping(value = "/user/info", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <User>> userList() {
        return ServiceResult.success(userService.userList());
    }

    @ApiOperation(value = "用户信息")
    @GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <User> userInfo(@ApiIgnore Principal principal) {
        return ServiceResult.success(userMapper.findOne(principal.getId()));
    }

    @ApiOperation(value = "修改用户信息")
    @Scope(role = UserRole.MANAGER)
    @PutMapping(value = "/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Boolean> userInfo(@RequestBody User user) {
        userMapper.updateSelective(user);
        return ServiceResult.SUCCESS;
    }

}
